package com.example.widget_lib.widget.sys.viewpager.transformer;

import ohos.agp.components.Component;
import ohos.agp.components.PageSlider;
import ohos.agp.components.StackLayout;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import static ohos.agp.components.ScrollHelper.AXIS_X;

/**
 * 转换器：xy缩放+透明度改变
 *  * @autor hongbing
 *  * @date 2019-11-14
 */
public class ScaleAlphaTransformer implements PageSlider.PageChangedListener {

    HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP,0,"ljkScaleAlphaTransformer");
    private final float SCALE_MAX = 0.6f;
    private final float ALPHA_MAX = 0.2f;
    PageSlider pageSlider;

    public ScaleAlphaTransformer(){

    }

    public void setSlider(PageSlider pageSlider){
        this.pageSlider = pageSlider;
    }

    public void transformPage(Component page, float position) {
        HiLog.debug(TAG, "tag = " + page.getTag() + "->position = " + position);
        if ((int) position < -1 || (int) position > 1) {
            return;
        }

        float scale = (position < 0)
                ? ((1 - SCALE_MAX) * position + 1)
                : ((SCALE_MAX - 1) * position + 1);
        float alpha = (position < 0)
                ? ((1 - ALPHA_MAX) * position + 1)
                : ((ALPHA_MAX - 1) * position + 1);

        if (position < 0) { // 目标屏-左边一屏的中心点设置
            page.setPivotX(page.getWidth());
            page.setPivotY(page.getHeight() / 2);
        } else {
            page.setPivotX(0);
            page.setPivotY(page.getHeight() / 2);
        }

        page.setScaleX(scale);
        page.setScaleY(scale);
        page.setAlpha(Math.abs(alpha));
    }


    @Override
    public void onPageSliding(int i, float v, int i1) {

        final int scrollX = (int) pageSlider.getScrollValue(Component.AXIS_X);
        final int childCount = pageSlider.getChildCount();
        HiLog.error(TAG,"i="+i+" v="+v+"  i1="+i1+"   childCount="+childCount);
        for (int k = 0; k < childCount; k++) {
            final Component child = pageSlider.getComponentAt(k);

            final float transformPos = (float) (child.getLeft() - scrollX) / child.getComponentSize().getSizeX();
            HiLog.error(TAG,"transformPos="+transformPos+"  lc.width="+child.getComponentSize().getSizeX()+"  scrollX="+scrollX+"  child.getLeft()="+child.getLeft());
            transformPage(child, transformPos);

        }
    }

    @Override
    public void onPageSlideStateChanged(int i) {

    }

    @Override
    public void onPageChosen(int i) {

    }


    private int getClientWidth(Component component) {
        return component.getLayoutConfig().width - component.getPaddingLeft() - component.getPaddingRight();
    }
}
